package com.bobo.serviceorder.service.impl;

import com.bobo.serviceorder.entry.TblOrderLock;
import com.bobo.serviceorder.lock.MysqlLock;
import com.bobo.serviceorder.lock.RedisLock;
import com.bobo.serviceorder.service.GrabService;
import com.bobo.serviceorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author bobo
 * @date 2021-04-12
 */
@Service
public class GrabRedisLockServiceImpl implements GrabService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisLock lock;

    private ThreadLocal<TblOrderLock> orderLockThreadLocal = new ThreadLocal<>();

    @Override
    public String grabOrder(int orderId, int driverId) {
        System.out.println("orderId=="+orderId+" driverId=="+driverId);
        TblOrderLock tblOrderLock = new TblOrderLock();
        tblOrderLock.setOrderId(orderId);
        tblOrderLock.setDriverId(driverId);
        System.out.println("tblOrderLock:"+tblOrderLock);
        orderLockThreadLocal.set(tblOrderLock);
        lock.setTblOrderLockThreadLocal(orderLockThreadLocal);

        lock.lock();
        try {
            System.out.println("司机:"+driverId+" 执行抢单逻辑");
            boolean result = orderService.grabOrder(orderId, driverId);
            if (result){
                System.out.println("司机:"+driverId+" 抢单成功");
                return "抢单成功";
            }else {
                System.out.println("司机:"+driverId+" 抢单失败");
                return "抢单失败";
            }
        } finally {
            lock.unlock();
        }
    }
}
